from aiogram import Router, types, F
from aiogram.filters import Command
from aiogram.fsm.context import FSMContext
from loguru import logger

from tg_bot.filters.user_filter import IsAdmin
from tg_bot.keyboards import inline, callback_factory as cf
from tg_bot.states.admin import AdminCmd

admin_main_router = Router()
admin_main_router.message.filter(IsAdmin())
admin_main_router.callback_query.filter(IsAdmin())


@admin_main_router.message(Command(commands='admin'))
async def admin_cmd(message: types.Message, state: FSMContext):
    """
    Админ меню команде /admin.
    :param message: Message.
    :param state: State.
    :return:
    """
    await state.clear()
    text = 'Добро пожаловать в админ меню.'
    key = await inline.admin_menu()
    await message.answer(text, reply_markup=key)
    await state.set_state(AdminCmd.main)


@admin_main_router.callback_query(cf.BackCall.filter(
    F.to == 'admin_menu'
))
async def back_to_admin_menu(call: types.CallbackQuery, state: FSMContext):
    """
    Переход в админ меню по инлайн кнопке "Назад".
    :param call: Callback.
    :param state: State.
    :return:
    """
    await state.clear()
    text = 'Добро пожаловать в админ меню.'
    key = await inline.admin_menu()
    try:
        await call.message.edit_text(text, reply_markup=key)
    except Exception as e:
        logger.warning(e)
        await call.message.answer(text, reply_markup=key)
    await state.set_state(AdminCmd.main)
